<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医院ID" prop="hospitalId">
        <el-input
          v-model="queryParams.hospitalId"
          placeholder="请输入医院ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室ID" prop="departmentId">
        <el-input
          v-model="queryParams.departmentId"
          placeholder="请输入科室ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="删除标记" prop="del">
        <el-select v-model="queryParams.del" placeholder="请选择删除标记" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hospital:hospitaldepartment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hospital:hospitaldepartment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hospital:hospitaldepartment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hospital:hospitaldepartment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hospitaldepartmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="医院名称" align="center" prop="hospitalName" />
      <!-- <el-table-column label="科室名称" align="center" prop="departmentName" /> -->
      <!-- 新增科室名称列，通过固定映射显示 -->
      <el-table-column label="科室名称" align="center">
        <template slot-scope="scope">
          {{ getDepartmentName(scope.row.departmentId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hospital:hospitaldepartment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hospital:hospitaldepartment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医院科室关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医院ID" prop="hospitalId">
          <el-input v-model="form.hospitalId" placeholder="请输入医院ID" />
        </el-form-item>
        <el-form-item label="科室ID" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择科室ID">
            <el-option
              v-for="(name, id) in departmentMap"
              :key="id"
              :label="`${id} - ${name}`"
              :value="id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="删除标记" prop="del">
          <el-select v-model="form.del" placeholder="请选择删除标记">
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDepartment } from "../../../api/hospital/department";
import { listhospitaldepartment, gethospitaldepartment, delhospitaldepartment, addhospitaldepartment, updatehospitaldepartment } from "@/api/hospital/hospitaldepartment"

export default {
  name: "hospitaldepartment",
  dicts: ['sys_normal_disable'], // 已移除department字典
  data() {
    return {
      departmentList:[],
      // 科室ID与名称的映射关系，根据实际业务数据修改
      departmentMap: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医院科室关联表格数据
      hospitaldepartmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: null,
        departmentId: null,
        del: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hospitalId: [
          { required: true, message: "医院ID不能为空", trigger: "blur" }
        ],
        departmentId: [
          { required: true, message: "科室ID不能为空", trigger: "change" }
        ],
        del: [
          { required: true, message: "删除标记不能为空", trigger: "change" }
        ]
      }
    }
  },
   // 页面创建时调用（获取医院科室关联列表 + 动态获取科室数据）
  created() {
    this.getList();
    this.getDepartmentList();// 新增：获取科室列表并生成映射
  },
  methods: {
    // 新增：获取科室列表并动态生成departmentMap
     getDepartmentList() {
          // 调用科室列表接口（后端返回科室数据）
          listDepartment().then(response => {
            // 存储后端返回的科室列表（response.rows是分页数据中的列表）
            this.departmentList = response.rows;

            // 生成ID到名称的映射（{ 科室ID: 科室名称 }）
            this.departmentMap = this.departmentList.reduce((map, item) => {
              // item是单个科室对象，包含id和name字段（需与后端返回字段一致）
              map[item.id] = item.name;
              return map;
            }, {});
          }).catch(error => {
            // 新增：错误处理（接口调用失败时提示）
            this.$modal.msgError("获取科室数据失败，请刷新页面重试");
            console.error("科室列表接口调用失败：", error);
          });
        },
    /** 根据科室ID获取科室名称 */
    getDepartmentName(departmentId) {
      // 如果找不到对应名称，显示原始ID
      return this.departmentMap[departmentId] || `未知科室(${departmentId})`;
    },
    /** 查询医院科室关联列表 */
    getList() {
      this.loading = true
      listhospitaldepartment(this.queryParams).then(response => {
        this.hospitaldepartmentList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$modal.msgError("查询失败，请重试")
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        hospitalId: null,
        departmentId: null,
        del: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加医院科室关联"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      gethospitaldepartment(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改医院科室关联"
      }).catch(error => {
        this.$modal.msgError("获取数据失败，请重试")
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatehospitaldepartment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError("修改失败，请重试")
            })
          } else {
            addhospitaldepartment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError("新增失败，请重试")
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
     handleDelete(row) {
       this.$confirm('确定删除吗？', '提示', { type: 'warning' }).then(() => {
         delhospitaldepartment(row.id).then(response => { // 修正为导入的方法名
           this.$modal.msgSuccess('删除成功');
           this.getList();
         }).catch(() => {
           this.$modal.msgError('删除失败');
         });
       });
     },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hospital/hospitaldepartment/export', {
        ...this.queryParams
      }, `hospitaldepartment_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
